package leetcode.medium.findanagrams;

import java.util.*;

import util.annotation.Solved;


/**
 * <a href="https://leetcode.cn/problems/find-all-anagrams-in-a-string/?envType=study-plan-v2&envId=top-100-liked">
 *     438. 找到字符串中所有字母异位词
 * </a>
 */
@Solved
public class Solution {

    /**
     * <h2>解题思路</h2>
     * <p>
     *     todo
     * </p>
     */
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        Map<Character, Integer> charCountMap = new HashMap<>();
        Map<Character, Integer> runtimeCharCountMap = new HashMap<>();
        for (int i = 0; i < p.length(); i++) {
            char c = p.charAt(i);
            charCountMap.merge(c, 1, Integer::sum);
            runtimeCharCountMap.put(c, 0);
        }
        int i = 0, j = 0;
        while (j < s.length()) {
            if (!charCountMap.containsKey(s.charAt(j))) {  // 判断当前字符是否在目标字符集内，如果不在，就往后看
                j++;
                i = j;
                for (Character c : charCountMap.keySet()) {
                    runtimeCharCountMap.put(c, 0);
                }
                continue;
            }
            // 把当前字符添加到运行集
            runtimeCharCountMap.put(s.charAt(j), runtimeCharCountMap.get(s.charAt(j)) + 1);
            // 判断长度够不够
            if (j - i + 1 == p.length()) {
                if (runtimeCharCountMap.equals(charCountMap)) {
                    res.add(i);  // 满足就加到结果中
                }
                // 不满足就右移
                runtimeCharCountMap.put(s.charAt(i), runtimeCharCountMap.get(s.charAt(i)) - 1);
                i++;
            }
            j++;
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(new Test().findAnagrams("abab", "ab"));
    }
}

/**
 * 2024-09-09 再刷
 */
class Test {
    public List<Integer> findAnagrams(String s, String p) {
        int[] pCount = new int[26];
        for (int i = 0; i < p.length(); i++) {
            pCount[p.charAt(i) - 'a']++;
        }
        int[] sCount = new int[26];
        int i = 0, j = 0;
        List<Integer> res = new ArrayList<>();
        while (j < s.length()) {
            if (j - i < p.length()) {
                sCount[s.charAt(j) - 'a']++;
                j++;
            } else if (j - i == p.length()) {
                if (Arrays.equals(sCount, pCount)) {
                    res.add(i);
                }
                sCount[s.charAt(i) - 'a']--;
                i++;
                sCount[s.charAt(j) - 'a']++;
                j++;
            }
        }
        if (Arrays.equals(sCount, pCount)) {
            res.add(i);
        }
        return res;
    }
}
